package com.ubaer.zsycz.inject.modules;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ubaer.zsycz.components.retrofit.factory.DoubleDefault0Adapter;
import com.ubaer.zsycz.components.retrofit.factory.GsonDConverterFactory;
import com.ubaer.zsycz.components.retrofit.factory.IntegerDefault0Adapter;
import com.ubaer.zsycz.components.retrofit.factory.LongDefault0Adapter;
import com.ubaer.zsycz.httpapi.HttpService;
import com.ubaer.zsycz.inject.Constants;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * author：lsw
 */
@Module
public class ApiModule {

    @Provides
    @Singleton
    public HttpService providesLoginService(OkHttpClient okHttpClient) {
        return getDefaultRetrofit(okHttpClient).create(HttpService.class);
    }

    private Retrofit getDefaultRetrofit(OkHttpClient okHttpClient) {
        return new Retrofit.Builder()
                .baseUrl(Constants.HOST)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonDConverterFactory.create(buildGson()))
                .build();
    }


    /**
     * 增加后台返回""和"null"的处理
     * 1.int=>0
     * 2.double=>0.00
     * 3.long=>0L
     *
     * @return
     */
    public Gson buildGson() {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
                .registerTypeAdapter(int.class, new IntegerDefault0Adapter())
                .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                .registerTypeAdapter(Long.class, new LongDefault0Adapter())
                .registerTypeAdapter(long.class, new LongDefault0Adapter())
                .create();
        return gson;
    }

}
